package com.jindi.jacococli.biz.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

public class ProcessUtils {

    public static final Logger LOGGER = LoggerFactory.getLogger(ProcessUtils.class);

    public static boolean execCommand(String command, File workingDir) {
        try {
            Process exec = Runtime.getRuntime().exec(command, null, workingDir);
            inputStreamToString(exec);
            exec.waitFor();
            LOGGER.info("================================");
        } catch (Exception e) {
            LOGGER.error("command error!", e);
            return false;
        }
        return true;

    }
    private static void inputStreamToString(Process exec) {
        new Thread(() -> {
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(exec.getInputStream()))) {

                String line;
                while ((line = reader.readLine()) != null) {
                    LOGGER.info("execute line:{}", line);
                }
            } catch (IOException e) {
                LOGGER.error("read error!", e);
            }
        }).start();
        new Thread(() -> {
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(exec.getErrorStream()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    LOGGER.info("execute error line:{}", line);
                }
            } catch (IOException e) {
                LOGGER.error("read error input!", e);
            }
        }).start();
    }
}
